# coding=utf-8
import pyautogui
import pygetwindow as gw
from PIL import ImageGrab
from PIL import Image
from paddleocr import PaddleOCR, draw_ocr
#import easyocr
import time
import cv2
import os
import subprocess
import requests
 
def close_notepad():
    # 关闭所有记事本窗口的命令
    cmd = 'taskkill /im notepad.exe /f'
    # 执行命令
    os.system(cmd)

# 识别文字
g_ocr = PaddleOCR(use_angle_cls=False, use_gpu=True)  # 如果不使用GPU，请设置use_gpu为False
 
# Create an OCR reader object
#g_easyocr = easyocr.Reader(['ch_sim'])


def calculate_center(points):
    # 初始化总和
    sum_x, sum_y = 0, 0
    # 计算总和
    for x, y in points:
        sum_x += x
        sum_y += y
    # 计算平均值得到中心点坐标
    center_x, center_y = sum_x / len(points), sum_y / len(points)
    return (center_x, center_y)

def calculate_center2(x, y, w, h):
    return ((x+w)//2, (y+h)//2)

def checkGreenPoint(image, x, y):
    r, g, b = image.getpixel((x, y))
    return (r == 84 and g == 255 and b == 255)

def checkRedPoint(image, x, y):
    r, g, b = image.getpixel((x, y))
    return (r == 255 and g == 61 and b == 61)

def checkWhitePoint(image, x, y):
    r, g, b = image.getpixel((x, y))
    return (r == 214 and g == 179 and b == 180)

def closeSmallWindow():
    closeimage = Image.open('./op.png')
    width, height = closeimage.size
    print(width, height)
    for y in range(height):
        for x in range(width):
            if checkWhitePoint(closeimage, x, y) and not checkWhitePoint(closeimage, x+1, y) and not checkWhitePoint(closeimage, x, y+1) \
            and checkWhitePoint(closeimage, x+1, y+1) and not checkWhitePoint(closeimage, x-1, y) and not checkWhitePoint(closeimage, x, y-1) \
            and checkWhitePoint(closeimage, x-1, y-1) and checkWhitePoint(closeimage, x+1, y-1) and checkWhitePoint(closeimage, x-1, y+1):
                print("close find")
                print(617 + x, 311 + y)
                pyautogui.click(617 + x, 311 + y)

def checkContainKey(image_path, key):
    global g_ocr
    #image=cv2.imread(image_path)
    #image=cv2.resize(iamge, (300, 180))

    # rec_result = g_easyocr.readtext(image_path)
    # for idx in range(len(rec_result)):
    #     res = rec_result[idx]
    #     print(res)
    #     #for line in res:
    #     boxes = res[0]
    #     center = calculate_center(boxes)
    #     print(center)
    #     print(res[1])
    #     if res[1] == key:
    #         return center
    rec_result = g_ocr.ocr(image_path, cls=False)
    for idx in range(len(rec_result)):
        res = rec_result[idx]
        for line in res:
            boxes = line[0]
            center = calculate_center(boxes)
            print(line[1][0])
            if line[1][0] == key:
                return center
    return None

def doStart(x, y):
    pyautogui.doubleClick(x,y)
    time.sleep(2)
    #opDlg = ImageGrab.grab()
    region_width = 759
    region_height = 460
    x = 617
    y = 311
    opDlg = ImageGrab.grab(bbox=(x, y, x+region_width, y+region_height))
    print(x, y)
    opDlg.save('./op.png')
    center = checkContainKey('./op.png', '操作')
    time.sleep(1)
    if center is not None:
        print(center[0] + x, center[1] + y)
        pyautogui.click(center[0] + x, center[1] + y)
        time.sleep(1)
        #detailDlg = ImageGrab.grab()
        region_width = 759
        region_height = 677
        x = 617
        y = 311
        detailDlg = ImageGrab.grab(bbox=(x, y, x+region_width, y+region_height))
        detailDlg.save('./detail.png')
        detailCenter = checkContainKey('./detail.png', '明细数据导出')
        if detailCenter is not None:
            pyautogui.click(detailCenter[0] + x, detailCenter[1] + y)
            time.sleep(1)
            pyautogui.press('enter')
            time.sleep(1)
            pyautogui.press('enter')
            time.sleep(1)
        close_notepad()
        time.sleep(1)
    closeSmallWindow()

def doGetData():
    # 等待1秒
    time.sleep(1)
    # 截取屏幕截图
    screenshot = ImageGrab.grab()
    # 保存截图到文件，使用活动窗口标题作为文件名
    screenshot.save('./screenshot.png')

    # 获取图像的宽度和高度
    # 打开图像
    image = Image.open('./screenshot.png')
    width, height = image.size
    # 遍历图像的每个像素点
    for y in range(height):
        for x in range(width):
            # 获取像素点的RGB值
            r, g, b = image.getpixel((x, y))
            # # 检测跌幅的点
            if checkGreenPoint(image, x, y) and checkGreenPoint(image, x+1, y) and checkGreenPoint(image, x, y+1) \
            and checkGreenPoint(image, x+1, y+1) and not checkGreenPoint(image, x-1, y) and not checkGreenPoint(image, x, y-1) \
            and not checkGreenPoint(image, x-1, y-1) and not checkGreenPoint(image, x+1, y-1) and not checkGreenPoint(image, x-1, y+1):
                #print("green:", x, y)
                doStart(x, y)
                continue
            # 检测涨幅的点
            if checkRedPoint(image, x, y) and checkRedPoint(image, x+1, y) and checkRedPoint(image, x, y+1) \
            and checkRedPoint(image, x+2, y) and checkRedPoint(image, x+3, y) and checkRedPoint(image, x+4, y) \
            and checkRedPoint(image, x+5, y) and checkRedPoint(image, x+6, y) and checkRedPoint(image, x+7, y) \
            and not checkRedPoint(image, x+2, y+1) and not checkRedPoint(image, x+3, y+1) and not checkRedPoint(image, x+4, y+1) \
            and not checkRedPoint(image, x+5, y+1) and not checkRedPoint(image, x+6, y+1) and not checkRedPoint(image, x+7, y+1) \
            and not checkRedPoint(image, x+1, y+1) and not checkRedPoint(image, x-1, y) and not checkRedPoint(image, x, y-1) \
            and not checkRedPoint(image, x-1, y-1) and not checkRedPoint(image, x+1, y-1) and not checkRedPoint(image, x-1, y+1):
                check = False
                if checkRedPoint(image, x+32, y+5) and checkRedPoint(image, x+32, y+11):
                    check = True
                if not check:
                    print("red:", x, y)
                    doStart(x, y)
                continue

 
file = open("./20240902.txt", "r")
time.sleep(5)
while True:
    pyautogui.moveTo(1456, 1058)
    line = file.readline()
    line = line.strip()
    print(line)
    if line is not None:
        for char in line:
            print(char)
            pyautogui.press(char)    
            time.sleep(0.1)
        pyautogui.press('enter')
        doGetData()
    else:
        break
file.close()

        

time.sleep(1000)


        
